$m(function(args) {	
	var dataSourceCode = args.dataSourceCode;
	var selectCallBack = args.callback;
	var allDataSources = args.allDataSources;
	//是否被关联数据集引用着，如果引用着，选择表时，不能选规则数据集以及SQL数据集
	var isRefByChartSet = args.isRefByChartSet;
	var $this = this;
	var $mainDialog = this.element;
	
	var $searchComp = $mainDialog.find('#tempo-import-mapping-table-search');
	var $treeComp = $mainDialog.find('#tempo-import-mapping-table-tree');
	var $loadmoreComp = $mainDialog.find('#tempo-import-mapping-table-loadmore');
	
	var $tableSortButton = $mainDialog.find('#tempo-dataview-table-sort-button');
	
	
	/**
	 * 初始化入口
	 */
	var init = function(){
		$mainDialog.dialog({
			title:TempoUtils.locale("resource.select_table"),
			width:300,
			height:500,
			modal:true,
			resizable:false,
			close:function(){
				$mainDialog.dialog("destroy").remove();
			},
			open:function(){
				render.render();
			},
			buttons:[{
				type: 'ok',
				click:function(){
					var getSelected = $treeComp.tree('getChecked');
					if(!getSelected || getSelected.length <=0){
						$("<div/>").alert({
							msg:TempoUtils.locale("resource.please_select_dataset")
						});
						return; 
					}
					if(selectCallBack){
						selectCallBack.call($this,getSelected[0]);
					}
					$mainDialog.dialog("close"); 
				}
			},{
				type : 'cancel',
				click:function(){
					$mainDialog.dialog("close"); 
				}
			}]
		});
	}
	
	
	/**
	 * 渲染器
	 */
	var render = {
			render:function(){
				render.renderSearch();
				
				var sortParam = {}
				var currentDataSource = getCurrentDataSourceInfo();
				if(currentDataSource.isModel != 1){
					sortParam['sortBy'] = "abc";
					sortParam['sortType'] = "asc";
				}
				render.loadTargetTable({},null,sortParam);
				render.renderTableButton();
			},
			
			/**
			 * 加载更多
			 */
			loadMoreTargetTable:function(pagerParam,searchWord,sortParam){
				var progress = $("<div/>").tempoprogressbar();
				clearLoadMoreButton();
				$.ajax({
					url:contextPath + '/resourceimpexp/getTables',
					data:{
						start:pagerParam.start,
						end:pagerParam.end,
						code:dataSourceCode,
						searchWord:searchWord,
						isRefByChartSet:isRefByChartSet,
						sortBy:sortParam.sortBy,
						sortType:sortParam.sortType,
						sortByDir:sortParam.sortByDir,
						sortByDirType:sortParam.sortByDirType
					},
					type:"post",
					success:function(resultData){
						progress.tempoprogressbar("destroy");
						if(resultData.flag){
							var data = resultData.data;
							data = render.formatTableShowText(data);
							for(var i=0;i<data.length;i++){
								$treeComp.tree("addNode",data[i]);
							}
							if(resultData.isNeedPage === true){
								renderLoadMoreButton({
									"start":resultData.currentPageNum
								});
							}
						}else{
							$("<div/>").alert({
								msg:resultData.msg
							});
						}
					}
				});
			},
			/**
			 * 加载数据表
			 */
			loadTargetTable:function(pagerParam,searchWord,sortParam){
				var progress = $("<div/>").tempoprogressbar();
				$.ajax({
					url:contextPath + '/resourceimpexp/getTables',
					data:{
						start:pagerParam.start,
						end:pagerParam.end,
						code:dataSourceCode,
						searchWord:searchWord,
						isRefByChartSet:isRefByChartSet,
						sortBy:sortParam.sortBy,
						sortType:sortParam.sortType,
						sortByDir:sortParam.sortByDir,
						sortByDirType:sortParam.sortByDirType
					},
					type:"post",
					success:function(resultData){
						progress.tempoprogressbar("destroy");
						if(resultData.flag){
							render.renderTree(resultData);
							$treeComp.data('sort-param',sortParam);
						}else{
							$treeComp.data('sort-param',null);
							$("<div/>").alert({
								msg:resultData.msg
							});
						}
					}
				})
			},
			/**
			 * 渲染搜索框
			 */
			renderSearch:function(){
				$searchComp.searchbar({
					auto:true,
					width:'255px',
					isEnter:true,
					placeholder:TempoUtils.locale("resource.please_input_table_name"),
					onSearch:function(searchWord){
						var currentDataSource = getCurrentDataSourceInfo();
						if(currentDataSource.isModel == 1){
							$treeComp.find(".tempo-tree-item").each(function(){
								var treeData = $(this).data("data");
								if(treeData.isTable){
									var name = treeData.name.toUpperCase();
									var title = treeData.title.toUpperCase();
									var targetData = $.trim(searchWord).toUpperCase();
									if(targetData){
										if(name.indexOf(targetData) >= 0 || title.indexOf(targetData) >= 0 ){
											$(this).parent().show();
										}else{
											$(this).parent().hide();
										}
									}else{
										$(this).parent().show();
									}
								}
							});
						}else{
							var sortParam = $treeComp.data('sort-param');
							render.loadTargetTable({},searchWord,sortParam);
						}
					}
				});
			},
			
			/**
			 * 渲染数据表的树
			 */
			renderTree:function(treeData){
				if($treeComp.hasClass("tempo-tree")){
					$treeComp.tree('destroy');
				}
				
				clearLoadMoreButton();
				
				$treeComp.tree({
					data:render.formatTableShowText(treeData.data),
					url:contextPath + '/resourceimpexp/getColumns',
					multiSelect:false,
					checkbox:true,
					onBeforeExpand:function(data,param){
						if(data.isColumn){
							delete param.dataSourceCode;
							return;
						}
						var catalog = data.catalog;
						var schema = data.schema;
						var tableName = data.name;
						var sql = data.sql;
						param.dataSourceCode = dataSourceCode;
						if(data.type == 'MSQL'){
							param.sql = sql;
						}else{
							param.tableName = tableName;
							param.schema = schema;
							param.catalog = catalog;
						}
					},
					onBeforeRender:function(renderData){
						return renderData.data;
					},
					onClickItem:function(nodeData){
						return false;
					},
					onCheck:function(data){
						if(data.isColumn || data.isDirection){
							return false;
						}
						return true;
					}
				});
				
				if(treeData.isNeedPage === true){
					renderLoadMoreButton({
						"start":treeData.currentNum
					});
				}
			},
			
			/**
			 * 处理显示字段
			 */
			formatTableShowText:function(data){
				var dataSource = getCurrentDataSourceInfo();
				if(dataSource.isModel == 1){
					return data;
				}
				if(!data || data.length<=0){
					return data;
				}
				var dataItem,catalog,schema,tableName,title;
				for(var i=0;i<data.length;i++){
					dataItem = data[i];
					tableName = dataItem.name;
					title = dataItem.title;
					schema = dataItem.schema;
					catalog = dataItem.catalog;
					catalog = !catalog ? "" : catalog + ".";
					if(dataItem.type == 'TABLE' || dataItem.type == 'VIEW'){
						data[i].title = title + "(" + catalog + schema + ")";
					}
				}
				return data;
			},
			renderTableButton:function(){
				$tableSortButton.unbind('click').bind('click',function(e){
					var currentDataSource = getCurrentDataSourceInfo();
					var dataSourceCode = currentDataSource.code;
					var isModel = currentDataSource.isModel;
					var sortParam = $treeComp.data('sort-param') || {};
					TempoUtils.tableSortEvent(e,dataSourceCode,isModel,sortParam,function(metaDataModel){
						var val = $searchComp.find('input').val();
						render.loadTargetTable({},val,metaDataModel);
					});	
				});
			}
			
	}
	
	/**
	 * 清除加载更多按钮
	 */
	var clearLoadMoreButton = function(){
		$loadmoreComp.empty();
	}
	
	
	/**
	 * 加载更多按钮
	 */
	var renderLoadMoreButton = function(pager){
		var div = $("<div/>",{
			"id":"tempo-import-resource-tables-loading",
			"style":"text-align:center;cursor:pointer",
			"text":TempoUtils.locale("resource.load_more")
		}).appendTo($loadmoreComp).data("pager-data",pager);
		div.unbind("click").bind("click",function(){
			var pagerInfo = $(this).data("pager-data");
			var pagerParam = {};
			pagerParam["start"] = pagerInfo.start;
			pagerParam["end"] = pagerInfo.end;
			var searchWord = $searchComp.find('input').val();
			var sortParam = $treeComp.data('sort-param');
			render.loadMoreTargetTable(pagerParam,searchWord,sortParam);
		});
	}
	
	/**
	 * 当前数据源信息
	 */
	var getCurrentDataSourceInfo = function(){
		if(allDataSources && allDataSources.length > 0){
			for(var i=0;i<allDataSources.length;i++){
				if(allDataSources[i].code == dataSourceCode){
					return allDataSources[i];
				}
			}
		}
		return null;
	}
	!function(){
		init();
	}();
});